from test01app import models
import json
from django.shortcuts import render

def _out_log(request):

    contains = json.loads(_open_andreadfile(request))
    #从upload.html页面获取用户输入到执行人和版本号
    people = request.POST.get("people", None)
    version = request.POST.get("version", None)
    if (contains):
        models.result.objects.create(bug_num=contains['total'], anr_num=contains['anr'],
                                     crash_num=contains['crash'], exception_num=contains['exception'],monkey_is_finish=contains['is_finish'],
                                     name=people, version_num=version, remark="写死到备注")
        list = models.result.objects.all()
        return list
    else:
        models.result.objects.create(bug_num=0, name=people, version_num=version, remark="写死到备注")
'''
_open_andreadfile用于获取在upload.html页面上传到文件名
并从上传到服务器到目录中打开并读取该文件内容
'''
def _open_andreadfile(request):
    #通过request获取上传到文件名
    File = request.FILES.get("myfile", None)
    #拿到上传到服务器/test01app/temp_file/文件到绝对路径
    log_out_str = "./test01app/temp_file/" + File.name
    #打开文件并将读取到到文本内容赋给s
    log_content = open(log_out_str, "r")
    s = log_content.read()
    #使用count函数统计该文本中字符A出现到次数
    #是否为ANR异常
    anr = s.count('ANR')
    #是否为Crash
    crash = s.count('CRASH')
    #是否发生Exception
    exception = s.count('Exception')
    #是否发生正常结束
    monkey_finish = s.count('Monkey finished')
    #合计统计
    total = anr+crash+exception
    is_finish = False
    if (monkey_finish > 0):
        is_finish = True
    log_content.close()
    _result_list =json.dumps({'anr': anr, 'crash': crash, 'exception': exception, 'is_finish': is_finish, 'total': total})
    return _result_list
